#!/bin/bash

die() {
    echo "$1"
    exit 1
}

cleanup() {
    ls -1 | grep -vE '^(inst|mbs)' | xargs rm -rf
    rm -f .fin
}

if [ ! "$2" ]
then
    echo 'Use: mbs_build <packet path> <system>'
    exit 1
fi
PACKETDIR="$1"
SYSTEM="$2"

# If we're building more than one, just call mbs_build multiple times
if [ "$3" ]
then
    shift
    while [ "$1" ]
    do
        "$0" "$PACKETDIR" "$1"
        shift
    done
    exit 0
fi

# Get the absolute packet dir
OLDPWD="$PWD"
cd "$PACKETDIR"
PACKETDIR="$PWD"
cd "$OLDPWD"

cd "`dirname $0`"

# Make sure the packet is there
if [ ! -e "$PACKETDIR/packet.tar.bz2" ]
then
    echo "$PACKETDIR/packet.tar.bz2"' does not exist.'
    exit 1
fi
PACKET="$PACKETDIR/packet.tar.bz2"
mkdir "$PACKETDIR"/results 2> /dev/null
RESULT="$PACKETDIR/results"

# Make sure the system exists
if [ ! -e "systems/$SYSTEM/system" ]
then
    echo 'System '$SYSTEM' does not exist.'
    exit 1
fi

# Load in the system
. systems/"$SYSTEM"/system

# Copy in mbs_run.sh
cp -f mbs_run.sh "$SYS_DIR/"

# Get to the system dir
cd "$SYS_DIR" || die "$SYS_DIR does not exist."
cleanup # pre-cleanup

# Extract the packet
tar jxf "$PACKET" || die "Failed to extract the packet."
if [ ! -e go.sh ]
then
    die "The packet does not include go.sh"
fi

# Add some environment info
( echo 'export MBS_SYSTEM='"$SYSTEM" ; cat go.sh ) > go.sh.new
mv -f go.sh.new go.sh

# Run it
bash -cx "$SYS_RUN"

mbs_build_prime() {
    # Wait for it to finish
    while [ ! -e .fin ]
    do
        sleep 1
    done

    # End it
    bash -cx "$SYS_END"

    # Collect the result and log
    if [ -e "result" ]
    then
        cd result || die "Failed to cd to result/"
        tar cf ../result.tar *
        cd .. || die "Failed to cd out of result/"
        mv -f result.tar "$RESULT"/"$SYSTEM".tar
    fi
    mv -f log.txt "$RESULT"/"$SYSTEM".txt || die "Failed to transfer the log."

    # And, for debugging, everything else
    tar jcf "$RESULT"/"$SYSTEM"-state.tar.bz2 *

    # Clean up
    cleanup
}

if [ "$SYS_BACKGROUND" = "yes" ]
then
    mbs_build_prime &
else
    mbs_build_prime
fi
